package psn.zjk.common.jdk8;

import java.lang.ref.SoftReference;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 *  结论：int类型 foreach性能更好
 * @author zhangjk
 * @CREATE_TIME 2020/12/11 15:37
 */
public class ForEachTest {


    public static void main(String[] args) {
        test(10000);
        System.out.println("1w");
        test(1000000);
        System.out.println("100w");
        test(10000000);
        System.out.println("1000w");
    }

    public static void test(int size) {
        SoftReference<List<Integer>> xx = createData(size);
        List<Integer> data = xx.get();
        long now = now();
        AtomicInteger sum = new AtomicInteger();
        for (Integer datum : data) {
            sum.addAndGet(datum);
        }
        System.out.println(now() - now);
        ;
        sum.set(0);
        now = now();
        data.forEach(integer -> {
            sum.addAndGet(integer);
        });
        System.out.println("forEach:" + (now() - now));
        ;
        now = now();
        sum.set(0);
        data.stream().forEach(integer -> {
            sum.addAndGet(integer);
        });
        System.out.println("stream:" + (now() - now)+sum.get());
        ;
        now = now();
        sum.set(0);
        data.parallelStream().forEach(integer -> {
            sum.addAndGet(integer);
        });
        System.out.println("parallelStream:" + (now() - now)+sum.get());
        xx = null;
        System.gc();
    }

    public static long now() {
        return System.currentTimeMillis();
    }

    private static SoftReference createData(long size) {
        return new SoftReference<List>(new Random().ints(size).boxed().collect(Collectors.toList()));
    }

}